package com.buho29.rcmanager;

import java.io.File;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.buho29.rcmanager.bd.DatabaseAdapter;
import com.buho29.rcmanager.bd.TableAlarm;
import com.buho29.rcmanager.bd.TableDamage;
import com.buho29.rcmanager.bd.TableModel;
import com.buho29.rcmanager.bd.TablePower;
import com.buho29.rcmanager.bd.TablePowerItem;
import com.buho29.rcmanager.bd.TableStatistic;
import com.buho29.rcmanager.utils.Format;
import com.buho29.rcmanager.utils.Make;

public class ModelView extends Activity {
	
	private DatabaseAdapter mDbAdapter;
	private TableModel mDbTableModel = new TableModel();
	private TableDamage mDbTableDamage= new TableDamage();
	private TableStatistic mDbTableStatistic = new TableStatistic();
	private TextView mText;
	private TextView mTextModel;
	private Button mAlarm;
	private Button mDamage;
	private Button mPower;

	private Long mId;
	
    private ImageView mImage;
	
 //   private static final int ACTIVITY_DRIVE=0;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.model_view);
        
        mDbAdapter = DatabaseAdapter.getInstance(this);
        mDbTableModel.setSQLiteDatabase(mDbAdapter.getDatabase());
        mDbTableDamage.setSQLiteDatabase(mDbAdapter.getDatabase());
        mDbTableStatistic.setSQLiteDatabase(mDbAdapter.getDatabase()); 
		
        Bundle extras = getIntent().getExtras();            
		if(savedInstanceState != null){
	       	mId = savedInstanceState.getLong(TableModel.COL_ROW_ID,0);
		}else if(extras != null){
			mId = extras.getLong(TableModel.COL_ROW_ID,0);
		}
        
        mImage = (ImageView) findViewById(R.id.iv);
        mText = (TextView)findViewById(R.id.tv);
        mTextModel = (TextView)findViewById(R.id.tv1);
        
        mAlarm = (Button)findViewById(R.id.bt1);
        mDamage = (Button)findViewById(R.id.bt2);
        mPower = (Button)findViewById(R.id.bt3);
        
        mAlarm.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
	        	Intent i = new Intent(ModelView.this, AlarmView.class);
		        i.putExtra(TableModel.COL_ROW_ID, mId);
		        i.putExtra(PowersView.CMD, PowersView.CMD_MODEL);
		        startActivityForResult(i, 1);
			}
		});
        
        mDamage.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
	        	Intent i = new Intent(ModelView.this, DamageView.class);
		        i.putExtra(TableModel.COL_ROW_ID, mId);
		        i.putExtra(PowersView.CMD, PowersView.CMD_MODEL);
		        startActivityForResult(i, 2);
			}
		});
        
        mPower.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
	        	Intent i = new Intent(ModelView.this, PowersView.class);
		        i.putExtra(TableModel.COL_ROW_ID, mId);
		        i.putExtra(PowersView.CMD, PowersView.CMD_MODEL);
		        startActivityForResult(i, 3);
			}
		});
        
		populateFields();
        
    }  
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        populateFields();
    }
    
    private void setImage(String path){
    	if(path == null){
    		mImage.setImageResource(R.drawable.no_found_image);
    		return;
    	}
    	File file = new File(path);
    	if(file.isFile()){

			BitmapDrawable d = (BitmapDrawable) BitmapDrawable.createFromPath(path);
			float width = Math.min(
				getWindowManager().getDefaultDisplay().getWidth(),
				getWindowManager().getDefaultDisplay().getHeight()	
			);
			float scale = width/d.getIntrinsicWidth();
			mImage.setImageDrawable(d);
			mImage.setLayoutParams(new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.FILL_PARENT,
					(int)(d.getIntrinsicHeight()*scale)));
    	}else {
    		mImage.setImageResource(R.drawable.no_found_image);
    	}
    	
    }
    
    private void populateFields() {
    		mDbTableModel.setId(mId);
        	mDbTableModel.load();
        		
        	String name = mDbTableModel.getName();
        	setImage(mDbTableModel.getImage());
        	mTextModel.setText(mDbTableModel.getDescription());
        	
        	SpannableStringBuilder text = new SpannableStringBuilder();
        	
        	mDbTableStatistic.loadModel(mId);
	    	buildResult(text, mDbTableStatistic.getTotal(), mDbTableStatistic.getCount(),
	    			mDbTableStatistic.getAverage(), mDbTableStatistic.getMin(),
	    			mDbTableStatistic.getMax(), Make.NEWLINE);
	    	
	    	text.append(Make.NEWLINE);
	    	
        	Make.appendResult(text, getText(R.string.accident), mDbTableModel.getAccident_count(), Make.NEWLINE);
        	// damage
        	mDbTableStatistic.loadDamage(mId);
        	Make.appendResult(text, getText(R.string.damage), mDbTableStatistic.getTotal()+"$", Make.NEWLINE);
        	
        	// power
        	TablePower tp = new TablePower();
        	tp.setSQLiteDatabase(mDbAdapter.getDatabase());
        	
        	Cursor cur = tp.fetchPowers(mId);
        	
        	String names = "" ;
        	for (int i = 0; i < cur.getCount(); i++) {
        		cur.moveToPosition(i);
				names += cur.getString(cur.getColumnIndexOrThrow(TablePowerItem.COL_NAME))+",";
			}
        	if(names.length()>1)
        		names = names.substring(0,names.length()-1);
        	cur.close();
        	
        	Make.appendResult(text, getText(R.string.power), names, Make.NEWLINE);
        	
        	// Alarm count
        	TableAlarm ta = new TableAlarm();
        	ta.setSQLiteDatabase(mDbAdapter.getDatabase());
        	
        	cur = ta.fetchModel(mId);
        	Make.appendResult(text, getText(R.string.alarm), cur.getCount(), Make.NEWLINE);
        	cur.close();
        	
        	mText.setText(text);
            mText.setMovementMethod(LinkMovementMethod.getInstance());
        	
        	setTitle(name);
    }
    
	private SpannableStringBuilder buildResult(SpannableStringBuilder ss, int total,int drive, 
			int average, int min , int max, String sep) {
        
		String[] fields = new String[]{
				(String)getText(R.string.total) ,
				(String)getText(R.string.drive) ,
				(String)getText(R.string.average) ,
				(String)getText(R.string.min) ,
				(String)getText(R.string.max)
		};
		
		Object[] value = new Object[]{
				Format.formatSecondsToString(total),
				drive,
				Format.formatSecondsToString(average),
				Format.formatSecondsToString(min),
				Format.formatSecondsToString(max)
		};
        Make.buildResult(ss, fields, value, sep);
     
        return ss;
    }    
        
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putLong(TableModel.COL_ROW_ID, mId);
    }
    
}
